package cn.lanyi.org.controller;

import cn.lanyi.basic.util.AjaxResult;
import cn.lanyi.basic.util.PageList;
import cn.lanyi.org.domain.Department;
import cn.lanyi.org.query.DepartmentQuery;
import cn.lanyi.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    // 根据id查询
    @GetMapping ("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Department getDepartmentById(@ApiParam(value="ID属性",required = true) @PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    @GetMapping ()
    public List<Department> findAllDepartments(){
        return departmentService.loadAll();
    }

    /**
     * 添加或者修改
     *
     * @param department
     * @return
     */
    @PutMapping()
    public AjaxResult saveDepartment(@RequestBody Department department) {
        try {
            if (null != department.getId()) {// 修改
                departmentService.update(department);
            } else {// 新增
                departmentService.save(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙，请重试");
        }
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteDepartmentById(@PathVariable("id") Long id) {
        try {
            departmentService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙，请重试");
        }
    }

    @PostMapping
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery query){
        return departmentService.queryData(query);
    }

    @PatchMapping
    public AjaxResult batchDepartment(@RequestBody List<Long> ids) {
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙，请重试");
        }
    }

    @GetMapping("/tree")
    public List<Department> tree() {
        return departmentService.tree();
    }


}
